package com.wusuowei.ucenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wusuowei.common.annotation.Log;
import com.wusuowei.common.constant.BusinessTypeEnum;
import com.wusuowei.common.utils.R;
import com.wusuowei.ucenter.model.po.SysRole;
import com.wusuowei.ucenter.model.po.SysRoleMenu;
import com.wusuowei.ucenter.model.po.SysUserRole;
import com.wusuowei.ucenter.model.vo.PageRoleVo;
import com.wusuowei.ucenter.service.ISysRoleMenuService;
import com.wusuowei.ucenter.service.ISysRoleService;
import com.wusuowei.ucenter.service.ISysUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lgy
 */
@Slf4j
//@PreAuthorize("isAuthenticated()")
@RestController
@RequestMapping("auth/role")
public class SysRoleController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserRoleService userRoleService;
    @Autowired
    private ISysRoleMenuService roleMenuService;

    @PreAuthorize("hasAuthority('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public R getInfo(@PathVariable String roleId)
    {
        return R.ok().setData(roleService.getById(roleId));
    }

    @PreAuthorize("hasAuthority('system:role:list')")
    @GetMapping
    public R findAll(Authentication authentication) {
        System.out.println(authentication);
        return R.ok().setData(roleService.list());
    }

    @PreAuthorize("hasAuthority('system:role:list')")
    @GetMapping("/page")
    public R findPage(PageRoleVo pagequery) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysRole::getId);
        //系统模块
        queryWrapper.like(StringUtils.isNotBlank(pagequery.getRoleName()),SysRole::getName,pagequery.getRoleName());
        //操作人员
        queryWrapper.like(StringUtils.isNotBlank(pagequery.getRoleKey()),SysRole::getRoleKey,pagequery.getRoleKey());
        //时间
        queryWrapper.ge(StringUtils.isNotBlank(pagequery.getStartTime()),SysRole::getCreateTime,pagequery.getStartTime());
        queryWrapper.le(StringUtils.isNotBlank(pagequery.getEndTime()),SysRole::getCreateTime,pagequery.getEndTime());
        return R.ok().setData(roleService.page(new Page<>(pagequery.getPageNum(), pagequery.getPageSize()), queryWrapper));
    }


    @PreAuthorize("hasAuthority('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    public R add(@RequestBody SysRole role) {
        roleService.save(role);
        return R.ok();
    }

    @PreAuthorize("hasAuthority('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public R edit(@RequestBody SysRole role) {
        roleService.updateById(role);
        return R.ok();
    }

    @PreAuthorize("hasAuthority('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{roleIds}")
    public R deleteBatch(@PathVariable List<Integer> roleIds) {
        long count = userRoleService.count(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getRoleId, roleIds));
        if(count>0){
            return R.error("无法删除，该角色还有绑定的用户");
        }
        roleService.removeBatchByIds(roleIds);
        return R.ok();
    }

    /**
     * 绑定角色和菜单的关系
     * @param roleId 角色id
     * @param menuIds 菜单id数组
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @Log(title = "角色管理", businessType = BusinessTypeEnum.INSERT)
    @PostMapping("/roleMenu/{roleId}")
    public R roleMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId);
        roleMenuService.remove(wrapper);
        roleService.setRoleMenu(roleId, menuIds);
        return R.ok();
    }

    @PreAuthorize("hasRole('admin')")
    @GetMapping("/roleMenu/{roleId}")
    public R getRoleMenu(@PathVariable Integer roleId) {
        return R.ok().setData(roleService.getRoleMenu(roleId));
    }

}

